const express = require('express')
const { CustomerAuth } = require('../utils/middles')
const { avatar } = require('../utils/upload')
const { db } = require('../utils/database')
const { makePassword, checkPassword } = require('../utils')
const { validate, validators } = require('../utils/validate')
const { setToken, getToken } = require('../utils/jwt')

// 不需要验证登入后才能使用的路由
const notAuthRouter = express.Router()
notAuthRouter
  /**
   *用户注册
   */
  .post(
    '/register',
    avatar.single('avatar'),
    validate([validators.username, validators.password, validators.nickname]),
    async (req, res) => {
      const { username, password, nickname } = req.body
      let customer = await db.findOne('select * from customers where username = ?', [username])
      if (customer) {
        return res.send({ success: false, message: '该用户已经存在' })
      }
      // 插入用户信息
      const [results] = await db.query(
        'insert into customers (avatar,username,password,nickname) values (?,?,?,?)',
        [
          req.file?.filename ? '/avatars/' + req.file?.filename : '',
          username,
          makePassword(password),
          nickname
        ]
      )
      // 查询刚刚插入的用户信息
      customer = await db.findOne('select * from customers where id = ?', [results.insertId])
      res.send({
        success: true,
        message: '注册成功！',
        customer
      })
    }
  )
  /**
   * 检查用户名
   */
  .get('/register/check', validate([validators.qUsername]), async (req, res) => {
    const { username } = req.query
    const exist = await db.findOne('select * from customers where username = ?', [username])
    if (exist) {
      return res.send({ success: false, message: '' })
    }
    res.send({ success: true, message: '' })
  })
  /**
   * 用户登录
   */
  .post('/login', validate([validators.username, validators.password]), async (req, res) => {
    const { username, password } = req.body
    // 根据用户名查询用户信息
    let user = await db.findOne('select * from customers where username = ?', [username])
    if (user && user.status) {
      return res.send({
        success: false,
        message: '用户账号封禁！'
      })
    }
    // 判断密码是否输入正确
    if (user && checkPassword(password, user.password)) {
      // 改变用户活跃状态
      // 在会话 （session）中保存用户信息
      req.session.userId = user.id
      return setToken({ userId: user.id, userName: user.username }).then((token) => {
        // 响应客户端
        res.send({
          success: true,
          message: '欢迎回来！',
          user,
          token: token
        })
      })
    }
    res.send({ success: false, message: '账号或密码错误' })
  })
  /**
   * 获取所有商品
   */
  .get(
    '/get_all_good',
    validate([
      validators.q_productName,
      validators.q_collect_num,
      validators.q_buy_num,
      validators.is_delete,
      validators.limit,
      validators.offset
    ]),
    async (req, res) => {
      const {
        product_name = '',
        collect_num = '',
        buy_num = '',
        is_delete = '',
        brand_id = '',
        tag_id = '',
        vendor_id = '',
        limit = '10',
        offset = '0'
      } = req.query
      let wheres = [`where id is not null`],
        orders = ['order by']
      if (product_name !== '') {
        wheres.push(`product_name like '%${product_name}%'`)
      }
      if (is_delete === '') {
        wheres.push('is_delete is not null')
      } else {
        wheres.push(`is_delete = '${is_delete}'`)
      }
      if (brand_id === '') {
        wheres.push('brand_id is not null')
      } else {
        wheres.push(`brand_id = '${brand_id}'`)
      }
      if (tag_id === '') {
        wheres.push('tag_id is not null')
      } else {
        wheres.push(`tag_id = '${tag_id}'`)
      }
      if (vendor_id === '') {
        wheres.push('vendor_id is not null')
      } else {
        wheres.push(`vendor_id = '${vendor_id}'`)
      }
      // 'asc' 升序 'desc' 降序
      if (collect_num !== '') {
        orders.push(`${orders.length > 1 ? ',' : ''}collect_num ${collect_num}`)
      }
      if (buy_num !== '') {
        orders.push(`${orders.length > 1 ? ',' : ''}buy_num ${buy_num}`)
      }
      const [results] = await db.query(
        `select * from goods ${wheres.join(' and ')} ${
          orders.length > 1 ? orders.join(' ') : ''
        } limit ${limit} offset ${offset} `
      )
      res.send({
        success: true,
        goods: results
      })
    }
  )
  /**
   * 获取商品详情
   */
  .get('/get_good_detail/:tid', validate([validators.tid]), async (req, res) => {
    let good = await db.findOne(`select * from goods where id = ?`, [req.params.tid])
    if (!good) {
      return res.send({
        success: false,
        message: '商品不存在'
      })
    }
    good.tag = await db.findOne(`select * from tags where id = ?`, [good.tag_id])
    good.brand = await db.findOne(`select * from brands where id = ?`, [good.brand_id])
    good.vendor = await db.findOne(`select * from vendors where id = ?`, [good.vendor_id])
    good.message = '该商品为下架商品！'
    res.send({
      success: true,
      good
    })
  })

// 需要验证登入后才能使用的路由
const router = express.Router()
router
  .use(CustomerAuth)
  // 获取当前用户信息
  .get('/userinfo', async (req, res) => {
    res.send({
      success: true,
      customer: req.user
    })
  })
  /**
   * 用户注销
   */
  .get('/logout', (req, res) => {
    // 清除 session 信息
    req.session.destroy()
    res.send({
      success: true,
      message: '用户注销成功'
    })
  })
  /**
   * 修改用户基本信息
   */
  .put(
    '/profile',
    avatar.single('avatar'),
    validate([validators.nickname, validators.gender]),
    async (req, res) => {
      const userinfo = req.user
      const { nickname, gender } = req.body
      await db.query('update customers set avatar = ?, nickname = ?,gender = ? where id = ?', [
        req.file?.filename ? '/avatars/' + req.file?.filename : userinfo.avatar,
        nickname,
        gender,
        req.user.id
      ])
      const customer = await db.findOne(
        'select avatar, nickname, gender from customers where id = ?',
        [req.user.id]
      )
      res.send({
        success: true,
        message: '修改成功',
        customer
      })
    }
  )
  /**
   * 修改用户密码
   */
  .put(
    '/updatePassword',
    validate([validators.oldPassword, validators.newPassword, validators.againPassword]),
    async (req, res) => {
      const { oldPassword, newPassword } = req.body
      // 根据用户名查询用户信息
      if (!checkPassword(oldPassword, req.user.password))
        return res.send({ success: false, message: '原密码错误，请重新输入！' })
      await db.query('update managers set password = ? where id = ?', [
        makePassword(newPassword),
        req.user.id
      ])
      if (oldPassword == newPassword)
        return res.send({ success: false, message: '新密码与原密码相同，请重新输入！' })
      res.send({
        success: true,
        message: '密码修改成功'
      })
    }
  )
  // 获取地址列表
  .get('/get_all_address', async (req, res) => {
    let [Address] = await db.query(
      'select * from addressLists where customer_id = ? and is_delete = 0',
      [req.user.id]
    )
    const results = Address.filter((i) => i.is_delete === 0)
    res.send({
      success: true,
      results
    })
  })
  // 新增地址
  .post(
    '/add_address',
    validate([
      validators.city,
      validators.person,
      validators.mobile,
      validators.details,
      validators.address
    ]),
    async (req, res) => {
      const { city, person, mobile, details, address, is_default = 0, type = '' } = req.body
      //查询地址是否重复
      const exist = await db.findOne(
        'select * from addressLists where address = ? and customer_id = ?',
        [address, req.user.id]
      )
      if (exist)
        return res.send({
          success: false,
          message: '该地址已经存在'
        })
      // 获取所有地址，判断是否为第一个地址，并且设置为默认地址
      let [addressLists] = await db.query(
        'select * from addressLists where customer_id = ? and isDelete = 0',
        [req.user.id]
      )
      const num = addressLists.length != 0 ? 0 : 1
      //插入地址信息
      const [results] = await db.query(
        'insert into addressLists (city, person, mobile, details, address, isDefault, customer_id) values (?,?,?,?,?,?,?)',
        [city, person, mobile, details, address, num, req.user.id]
      )
      const userAddress = await db.findOne('select * from addressLists where id = ?', [
        results.insertId
      ])
      res.send({
        success: true,
        message: '新增地址成功',
        userAddress
      })
    }
  )
// // 消费者修改地址
// .put(
//   '/addressLists/:tid',
//   validate([
//     validators.id,
//     validators.city,
//     validators.person,
//     validators.mobile,
//     validators.details,
//     validators.address
//   ]),
//   async (req, res) => {
//     let userAddress = await db.findOne(
//       'select * from addressLists where id = ? and customer_id = ?',
//       [req.params.tid, req.user.id]
//     )
//     if (!userAddress) return res.send({ success: false, message: '该地址信息不存在！' })
//     const { city, person, mobile, details, address, isDefault } = req.body
//     if (isDefault) {
//       const exist = await db.findOne(
//         'select * from addressLists where isDefault = 1 and customer_id = ?',
//         [req.user.id]
//       )
//       await db.query('update addressLists set isDefault = 0 where id = ?', [exist.id])
//     }
//     const num = isDefault ? 1 : 0
//     await db.query(
//       'update addressLists set city = ?, person = ?, mobile = ?, details = ?, address = ?, isDefault = ? where id = ?',
//       [city, person, mobile, details, address, num, req.params.tid]
//     )
//     userAddress = await db.findOne('select * from addressLists where id = ?', [req.params.tid])
//     res.send({ success: true, message: '地址修改成功', userAddress })
//   }
// )
// // 消费者删除地址
// .put('/addressLists/delete/:tid', validate([validators.id]), async (req, res) => {
//   const address = await db.findOne(
//     'select * from addressLists where id = ? and customer_id = ?',
//     [req.params.tid, req.user.id]
//   )
//   if (!address) return res.send({ success: false, message: '该地址信息不存在！' })
//   // 判断是否为默认地址，删除默认地址要给其他地址设置为默认地址
//   if (address.isDefault) {
//     let [addressLists] = await db.query(
//       'select * from addressLists where customer_id = ? and isDelete = 0',
//       [req.user.id]
//     )
//     let ids = addressLists.map((i) => {
//       return i.id
//     })
//     id = ids.filter((i) => i != address.id)
//     id.sort((a, b) => {
//       return a - b
//     })
//     await db.query('update addressLists set isDefault = 1 where id = ?', [id[0]])
//     await db.query('update addressLists set isDefault = 0 where id = ?', [address.id])
//   }
//   await db.query('update addressLists set isDelete = 1 where id = ?', [req.params.tid])
//   res.send({ success: true, message: '删除地址成功' })
// })

const Router = (app) => {
  app.use('/customer', notAuthRouter)
  app.use('/customer', router)
}

module.exports = { Router }
